import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {AuthService} from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private router: Router,
              private auth: AuthService) {
  }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (this.auth.isAuthenticated()) {
      return true;
    } else if (state.root.queryParams.code) {
      return this.auth.login(state.root.queryParams.code);
    } else if (location.href.indexOf('code=') > 0) {
      return this.auth.login(location.href.split('code=')[location.href.split('code=').length - 1]);
    }
    this.auth.loginPage();
    return false;
  }
}
